package com.wxboot.game.eliminate.modules.service;

import com.wxboot.game.eliminate.base.BombAreaPoint;
import com.wxboot.game.eliminate.base.JellyCell;
import com.wxboot.game.eliminate.base.JellyContext;
import com.wxboot.game.eliminate.modules.repository.JellyEliminateRepository;
import com.wxboot.game.eliminate.modules.service.cache.JellyCache;
import com.wxboot.game.eliminate.support.JellyBeanGenerator;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.UUID;

@Service
public class JellyEliminateService {

    @Autowired
    private JellyEliminateRepository jellyEliminateRepository;

    public String startJellyGameLevel(Integer level, JellyContext context) {
        String matrixStr = jellyEliminateRepository.getGameLevelMatrix(level);
        if (Objects.isNull(matrixStr)) {
            throw new RuntimeException("INVALID PARAMS");
        }

        String sessionId = UUID.randomUUID().toString()
                .replace("-", "").substring(0, 8);
        StringBuilder result = new StringBuilder(sessionId);
        result.append("\n").append(matrixStr);

        // 存入缓存
        JellyCell[][] jellyMatrix = JellyBeanGenerator.deserializeMatrix(matrixStr);
        JellyCache.userMatrixCache.put(sessionId, jellyMatrix);

        return result.toString();
    }

    public String moveJelly(String sessionId, JellyContext jellyContext, BombAreaPoint bombAreaPoint) {
        // 校验参数
        this.validatePoint(sessionId, bombAreaPoint);

        JellyCell[][] jellyMatrix = JellyCache.userMatrixCache.get(sessionId);
        jellyContext.setMatrixJellyCell(jellyMatrix);

        JellyEliminateExecutor executor = new JellyEliminateExecutor(jellyContext);
        // 引爆相应区域的果冻
        executor.invokeMove(bombAreaPoint);

        // 引爆后的结果重新放入缓存
        JellyCache.userMatrixCache.put(sessionId, jellyContext.getMatrixJellyCell());
        // 返回结果
        return jellyContext.getMatrix();
    }

    public void validatePoint(String sessionId, BombAreaPoint bombAreaPoint) {
        if (Objects.isNull(sessionId) ||
                ObjectUtils.anyNull(bombAreaPoint.getLeftUpCol(),
                        bombAreaPoint.getLeftUpRow(),
                        bombAreaPoint.getRightDownRow(),
                        bombAreaPoint.getRightDownCol())) {
            throw new RuntimeException("INVALID PARAMS");
        }

    }


}
